package br.com.news.web.utils;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDownload extends HttpServlet {

	private static final long serialVersionUID = 4253595550457227354L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		ObjetoDownload anexo = (ObjetoDownload) request.getSession().getAttribute("ObjetoDownload");
		
		if (anexo != null) {
			
			byte[] bytes = anexo.getArquivo();
			
			if (bytes != null) {
				response.setContentLength(bytes.length);
			}
			
			response.setContentType(anexo.getTipo());
			response.setHeader("Content-Disposition", "attachment;filename=\"" + anexo.getNome().substring(anexo.getNome().lastIndexOf("\\") + 1)+ "\"");
			
			
			ServletOutputStream ouputStream;
			try {
				ouputStream = response.getOutputStream();
				
				if (bytes != null) {
					ouputStream.write(bytes, 0, bytes.length);
				}
				
				ouputStream.flush();
				ouputStream.close();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
			
			// remove objeto da sessao
			request.getSession().setAttribute("ObjetoDownload", null);
		}
		
	}

}
